package com.yeskery.nut.util;

import com.yeskery.nut.core.HttpHeader;
import com.yeskery.nut.core.Request;
import com.yeskery.nut.core.Response;
import com.yeskery.nut.extend.auth.CrossConfiguration;

import java.util.Collection;
import java.util.Optional;

/**
 * 跨域工具类
 * @author YESKERY
 * 2024/6/20
 */
public class CrossUtils {

    /**
     * 私有化构造方法
     */
    private CrossUtils(){
    }

    /**
     * 获取请求跨域配置
     * @param crossConfigurations 跨域配置集合
     * @param request 请求对象
     * @param response 响应对象
     * @param finish 是否直接完成请求
     * @return 请求跨域配置
     */
    public static Optional<CrossConfiguration> getRequestCross(Collection<CrossConfiguration> crossConfigurations, Request request,
                                                                Response response, boolean finish) {
        Optional<CrossConfiguration> optional = crossConfigurations.stream()
                .filter(c -> "*".equals(c.getAllowedOrigins()) || c.getAllowedOrigins().equals(request.getHeader(HttpHeader.ORIGIN)))
                .findFirst();
        if (optional.isPresent()) {
            CrossConfiguration crossConfiguration = optional.get();
            response.addHeader("Access-Control-Allow-Origin", crossConfiguration.getAllowedOrigins());
            if (!StringUtils.isEmpty(crossConfiguration.getAllowedMethods())) {
                response.addHeader("Access-Control-Allow-Methods", crossConfiguration.getAllowedMethods());
            }
            if (!StringUtils.isEmpty(crossConfiguration.getAllowedHeaders())) {
                response.addHeader("Access-Control-Allow-Headers", crossConfiguration.getAllowedHeaders());
            }
            if (crossConfiguration.getMaxAge() != null) {
                response.addHeader("Access-Control-Max-Age", crossConfiguration.getMaxAge().toString());
            }
            if (crossConfiguration.getAllowedCredentials() != null) {
                response.addHeader("Access-Control-Allow-Credentials", crossConfiguration.getAllowedCredentials().toString());
            }
            if (finish) {
                response.writeEmpty();
            }
        }
        return optional;
    }
}
